package com.shop.service.impl;

import com.shop.dto.CarItem;
import com.shop.dto.InvoiceDTO;
import com.shop.dto.OrderItem;
import com.shop.mapper.CartMapper;
import com.shop.mapper.GoodsMapper;
import com.shop.mapper.OrderMapper;
import com.shop.model.Goods;
import com.shop.model.Invocei;

import com.shop.model.Order;
import com.shop.service.AlipayService;
import com.shop.service.CartService;
import com.shop.service.GoodsService;
import com.shop.service.OrderService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private CartService cartService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private AlipayService alipayService;
    @Autowired
    private RedisService redisService;



    @Override
    @Transactional
    public int addOrderInfo(Order order,Integer cartId) {
        int a=orderMapper.addOrderInfo(order);
        Goods goods=goodsMapper.selectById(order.getGoodid());
        Double num=order.getTotalMoney()/goods.getSalePrice().doubleValue();
        goodsMapper.reduceStock(order.getGoodid(),num.intValue());
        redisService.delete("","","");
        cartService.deleteCartbyId(cartId);
        if (a>0){
            a=1;
        }else {
            a=0;
        }
        return a;
    }

    @Override
    public List<Order> getAllOrders() {
        return orderMapper.selectAllOrders();
    }

    @Override
    public Order selectByOrderNo(String no) {
        return orderMapper.selectByOrderNo(no);
    }

    @Override
    public Order createOrder(Order order) {
        int result = orderMapper.addOrderInfo(order);
        if (result > 0) {
            return order;
        }
        return null;
    }

    @Override
    public Order getOrderByOrderNo(String orderNo) {
        return orderMapper.selectByOrderNo(orderNo);
    }

    @Override
    public List<Order> getOrdersByUserId(Integer userId) {
        return orderMapper.selectByUserId(userId);
    }

    @Override
    public boolean updateOrderStatus(String orderNo, String status, Date payTime) {
        int result = orderMapper.updateStatus(orderNo, status,payTime);
        return result > 0;
    }

    @Override
    @Transactional
    public boolean deleteOrder(Integer id) {
        Order order=orderMapper.selectById(id);
        if(!order.getStatus().equals("1")) {
            Goods goods=goodsMapper.selectById(order.getGoodid());
            Double num=order.getTotalMoney()/goods.getSalePrice().doubleValue();
            goodsMapper.reduceStock(goods.getId(),-num.intValue());
            redisService.delete("","","");
        }
        int result = orderMapper.deleteByOrderNo(id);
        return result > 0;
    }

    @Override
    public Order selectById(Integer id) {
        return orderMapper.selectById(id);
    }

//    @Override
//    public List<Order> searchOrders(String orderNo, Integer userId, String status) {
//        return orderMapper.selectByCondition(orderNo, userId, status);
//    }

    @Override
    public String submitOrder(Integer userId, Integer addressId, String telphone, String payType, HttpSession session) {
        // 1. 获取购物车数据
        List<CarItem> cartItems = cartService.getCar(Long.valueOf(userId));
        if (cartItems == null || cartItems.isEmpty()) return null;
        // 获取地址信息
//        Address address = addressService.getAddressById(addressId);
//        if (address == null) return null;
        // 1. 生成订单编号
        String orderNo = userId + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        Double totalMoney = cartService.getTotalPrice(userId).getPrice();
        // 2. 插入订单
        Order order = new Order();
        order.setNo(orderNo);
        order.setAddTime(String.valueOf(new Date()));
        order.setUserId(userId);
        order.setTotalMoney(totalMoney);
//        order.setAddress(address.getProvince() + address.getCity() + address.getArea() + address.getStreet());
//        order.setAccept(address.getAccept());
        order.setTelphone(telphone);
        order.setPayType(payType);
        order.setStatus("0"); // 未支付
//        orderMapper.insertOrder(order); // 需返回自增id

        // 3. 插入订单项
        for (CarItem item : cartItems) {
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(order.getId());
            orderItem.setGoodsId(item.getGoodid());
            orderItem.setName(item.getGoodname());
            orderItem.setImage(item.getGoodimage());
            orderItem.setPrice(item.getGoodprice());
            orderItem.setNum(item.getNum());
            orderMapper.insertOrderItem(orderItem);
        }
        return orderNo;
    }

    @Override
    @Transactional
    public String payOrder(Integer userId, String orderId) {
        // 1. 购物车里是否有数据
        List<CarItem> cartItems = cartService.getCar(Long.valueOf(userId));
        if (cartItems == null || cartItems.isEmpty()) return null;
        // 2. 判断库存
        for (CarItem item : cartItems) {
            // 判断库存
            Goods good = goodsService.findById(item.getGoodid());
            if (item.getNum() > good.getStock()) {
                return "fail:stock";
            }
        }
        // 3. 修改商品库存
        for (CarItem item : cartItems) {
            goodsService.reduceStock(item.getGoodid(), item.getNum());
        }
        // 清理购物车
        cartService.clearCart(Long.valueOf(userId));
//        cartService.clearCartItem(userId);
        // 更新订单状态
        this.updateOrderStatus(orderId, "已支付",new Date());
        return "success";
    }

    @Override
    public String createAlipayPayment(String orderNo, Double totalAmount, String subject) {
        return alipayService.createPayment(orderNo, totalAmount, subject);
    }

    @Override
    public void orderSuccess(String outTradeNo, Integer userId) {
        orderMapper.updateOrderStutus(outTradeNo,userId);
    }

    @Override
    public InvoiceDTO getInvoiceDTO(Integer orderId) {
        return orderMapper.selectInvoiceDTO(orderId);
    }

    @Override
    public Integer addInvoice(Map map) {
        Invocei invocei=new Invocei();
        invocei.setOrderId(Integer.parseInt(map.get("orderId").toString()));
        invocei.setTitle(map.get("title").toString());
        invocei.setOrderInfo("名称："+map.get("goodsName")+" 单价："+map.get("goodsPrice")+" 数量："+map.get("goodsNum")+" 总金额："+map.get("money"));
        invocei.setType(Integer.parseInt(map.get("type").toString()));
        invocei.setTaxId(map.get("tax_id").toString());
        invocei.setBankCard(map.get("bank_card").toString());
        invocei.setAddTime(new Date());

        orderMapper.addInvoice(invocei);
        return invocei.getId();
    }

    @Override
    public Invocei getInvoice(Integer id) {
        return orderMapper.getInvoice(id);
    }

    @Override
    public Invocei getInvoiceByOrderId(int orderId) {
        return orderMapper.getInvoiceByOrderId(orderId);
    }
}